from rest_framework.response import Response
from rest_framework.utils.serializer_helpers import ReturnDict  # 序列化中返回错误的类型
from rest_framework import serializers

class APIResponse(Response):
    # 格式化data
    def __init__(self, code=200, msg='success',
                 results=None, http_status=200, headers=None, exception=False, **kwargs):
        if isinstance(msg, ReturnDict):  # 判断序列化中是否返回错误
            for k, v in msg.items():
                msg = '{}:{}'.format(k, v[0])  # 获取到第一个错误即break
                break

        data = {
            'code': code,
            'msg': msg
        }
        if results is not None:
            data['data'] = results

        data.update(**kwargs)  # 将传入的其他数据放入data字

        # 处理完毕数据后，剩下的过程还是丢给Response类中的init做完
        super(APIResponse, self).__init__(
            data=data, status=http_status, headers=headers, exception=exception)


# def VueAPIResponse(self, queryset, results, data='data',page=True):
#     """
#     :param self:重写list必传
#     :param queryset: 过滤、搜索后的queryset
#     :param results: 必须是字典类型，且字典内data为查询、过滤、分页的结果
#     :param data: 列表数据默认存储在data中
#     :return: 返回Response
#     """
#     if not isinstance(results, dict):
#         raise serializers.ValidationError("results类型错误，必须是字典！")
#     if not isinstance(data, str):
#         raise serializers.ValidationError("data类型错误，必须是字符串！")
#     if data in results:
#         raise serializers.ValidationError("列表数据key与额外参数key冲突，请修改！")
#     if page:
#         page = self.paginate_queryset(queryset)
#         if page is not None:
#             results[data] = self.get_serializer(page, many=True).data
#             return self.get_paginated_response(results)
#
#     query_data = self.get_serializer(queryset, many=True)
#     if query_data.data:
#         results[data] =query_data.data[0]
#     else:
#         results[data] = []
#     return Response(results)


def VueAPIResponse(self,queryset,code=200,message='success',page=True,data=[]):
    """
    :param self:重写list必传
    :param code: 状态码
    :param self:重写list必传
    :param queryset: 过滤、搜索后的queryset
    :param results: 必须是字典类型，且字典内data为查询、过滤、分页的结果
    :param data: 列表数据默认存储在data中,如果有Data，直接进行返回
    :return: 返回Response
    """

    results = {}
    results['code']= code
    results['message'] = message
    results['data'] = {}

    if data:
        results['data'] = data
        return Response(results)

    if page:
        page = self.paginate_queryset(queryset)
        if page is not None:
            results['data']['list'] = self.get_serializer(page, many=True).data
            return self.get_paginated_response(results)

    query_data = self.get_serializer(queryset, many=True)
    # if hasattr(query_data,"data"):
    #     print('bbbbbbbbbbbb')
    #     results['data']['list'] = list(query_data.data)
    # else:
    #     results['data']['list'] = []
    return Response(results)